// carolsail

import GbzResManager from "../manager/GbzResManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GbzBox extends cc.Component {

    index: number = 0
    screwNum: number = 0
    screwNumMax: number = 3

    refresh(index: number) {
        this.index = index
        this.node.getComponent(cc.Sprite).spriteFrame = GbzResManager.ins.sprite(`gbz_box${index}`)
        const screwNode = this.node.getChildByName('screws')
        screwNode.children.forEach((screw, i) => {
            screw.getComponent(cc.Sprite).spriteFrame = GbzResManager.ins.sprite(`gbz_screw${index}`)
            screw.active = i < this.screwNum
        })
    }

    isActive() {
        let active = true
        const isLock = (Boolean)(this.node.getChildByName('lock'))
        const isScale = this.node.scale < 1
        if (isLock || isScale || this.screwNum >= this.screwNumMax) active = false
        return active
    }

    isLock() {
        return (Boolean)(this.node.getChildByName('lock'))
    }

    unlock() {
        if (this.node.getChildByName('lock')) this.node.getChildByName('lock').removeFromParent(true)
    }

    addScrewNum() {
        this.screwNum += 1
    }

    setScrewNum(num: number) {
        this.screwNum = num
    }

    checkFull() {
        let isFull = false
        if (this.screwNum >= this.screwNumMax) {
            const screwNode = this.node.getChildByName('screws')
            const index = screwNode.children.findIndex(screw => !screw.active)
            if (index < 0) isFull = true
        }
        return isFull
    }

    getScrewCurrent() {
        const screwNode = this.node.getChildByName('screws')
        const screw = screwNode.children[this.screwNum]
        return screw
    }
}
